package com.appsindy.common.action;

import com.appsindy.common.AppsindyConstants;
import com.appsindy.common.action.AppsindyBaseAction;
import com.appsindy.common.bo.GlobalUser;
import com.appsindy.common.bo.MenuLink;
import com.appsindy.common.dao.GlobalUserDAO;
import com.appsindy.common.service.AuthorizationServices;
import com.appsindy.reserv.ReservConstants;
import com.appsindy.reserv.bo.Counter;
import com.appsindy.reserv.bo.ShiftControlMap;
import com.appsindy.reserv.dao.ShiftControlDAO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.opensymphony.xwork2.Action;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class LoginAction extends AppsindyBaseAction implements SessionAware, ApplicationContextAware {
    
    private String userName;
    private String userPassword;
    private int counter;
    
    private Map<String, Object> session;
    private ApplicationContext applicationContext;
    
    private GlobalUserDAO globalUserDAO;
    private ShiftControlDAO shiftControlDAO;
    private AuthorizationServices authorizationServices;
    
    private List<Counter> counterList;
    
    @SuppressWarnings("unchecked")
	@SkipValidation
    public String execute() {
    	HttpSession httpSession = ServletActionContext.getRequest().getSession(true);
    	List<Counter> cntrList = (List<Counter>)httpSession.getAttribute("S_COUNTERS");
    	if(cntrList == null || cntrList.size() < 1){
    		cntrList = getShiftControlDAO().selectCounter(1);
    	}
    	
    	if(cntrList == null || cntrList.size() < 1){
    		setCounterList(new ArrayList<Counter>());
    	} else{
    		setCounterList(cntrList);
    	}
    	
    	httpSession.setAttribute("S_COUNTERS", getCounterList());
    	return INPUT;
    }

    public String login() {
    	HttpSession httpSession = ServletActionContext.getRequest().getSession(false);
    	log.info("Counter Id = " + getCounter());
        try {
        	Map<String, Object> params = new HashMap<String, Object>();
			params.put("userName", userName);
			params.put("userPassword", userPassword);
        	GlobalUser globalUser = getGlobalUserDAO().authenticateUser(params);
        	
            if(globalUser == null){
                addActionError("Username or Password is not correct !");
                return execute();
                
            } else{
            	
            	if(globalUser.getUserTypeId() == 130){	// Admin
            		setGlobalUser(globalUser);
	                session.put(AppsindyConstants.S_USER_LOGIN, globalUser);
            		httpSession.setAttribute(AppsindyConstants.S_USER_TYPE, ReservConstants.USER_TYPE_ADMIN);
                	return "admin";
                	
            	} else{		// Staff
            		if(getCounter() < 1){
            			addActionError("Please select counter.");
	                    return execute();
            		}
	                
	                //ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
	                /*try{
	                    SessionContextService sessionCtxSv = (SessionContextService)applicationContext.getBean("sessionContextService");
	                    if(sessionCtxSv != null){
	                       sessionCtxSv.setUserId(userVO.getUserId());
	                       sessionCtxSv.setUserFullName(userVO.getName());
	                       //sessionCtxSv.setUserGroup(userVO.getUserGroup());
	                       HttpServletRequest request = ServletActionContext.getRequest();
	                       try{
	                           //String hostname = InetAddress.getLocalHost().getHostName();
	                           InetAddress remoteInetAddress = InetAddress.getByName(request.getRemoteAddr());
	                           String hostname = remoteInetAddress.getCanonicalHostName();
	                           log.info("[LoginAction] Computer Name : " + hostname);
	                           sessionCtxSv.setRemoteHost(hostname);
	                       } catch(Exception e){
	                           log.error("[LoginAction] Error to get Computer Name : " + e);
	                           sessionCtxSv.setRemoteHost(request.getRemoteHost());
	                       }
	                       sessionCtxSv.setRemoteAddr(request.getRemoteAddr());
	                    }
	                } catch(Exception e){
	                    e.printStackTrace();
	                }*/
            		Counter cntrSelected = null;
            		List<Counter> cntrList = (List<Counter>)httpSession.getAttribute("S_COUNTERS");
            		if(cntrList != null){
            			for(int i=0; i<cntrList.size(); i++){
            				Counter cntr = cntrList.get(i);
            				if(cntr.getCounterId() == getCounter()){
            					cntrSelected = cntr;
            					break;
            				}
            			}
            		}
            		
	            	setGlobalUser(globalUser);
	                session.put(AppsindyConstants.S_USER_LOGIN, globalUser);
	                
	                httpSession.setAttribute(AppsindyConstants.S_USER_LOGIN, globalUser);
	                httpSession.setAttribute(AppsindyConstants.S_COUNTER, cntrSelected);
	                httpSession.setAttribute(AppsindyConstants.S_USER_TYPE, ReservConstants.USER_TYPE_STAFF);
                	return Action.SUCCESS;
            	}
            }
        } catch(Exception ex) {
            log.error("UserAuthenticateException : " + ex.toString());
            addActionError("Invalid Username or Password !");
        }
        return execute();
    }
    
    public void createMenu(){
    	List<MenuLink> menuLinks = getAuthorizationServices().getAllMenuLink();
    	if(menuLinks != null){
    		Map<String, Object> menuItems = new HashMap<String, Object>();
    		Map<String, Object> parents = new HashMap<String, Object>();
    		for(int i=0; i<menuLinks.size(); i++){
    			MenuLink menuLink = menuLinks.get(i);
    			menuItems.put(String.valueOf(menuLink.getLinkId()), menuLink);
    			//parents.put(key, value);
    		}
    	}
    	/*// prepare special array with parent-child relations
$menuData = array(
    'items' => array(),
    'parents' => array()
);
$result = mysql_query("SELECT link_id id, link_parent parentId, link_name name FROM menu_links  ORDER BY link_parent"); 

while ($menuItem = mysql_fetch_assoc($result)) {
    $menuData['items'][$menuItem['id']] = $menuItem;
    $menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];
}

// menu builder function, parentId 0 is the root
function buildMenu($parentId, $menuData)
{
    $html = '';
	$parent='';

    if (isset($menuData['parents'][$parentId]))
    {
		$menuClass= ($parentId==0) ? ' class="menu" id="menu"' : '';
		$parent= ($parentId==0) ? 0 : 1;	
        $html = "<ul{$menuClass}>\n";
		
        foreach ($menuData['parents'][$parentId] as $itemId)
        {
			//subment
			$result=mysql_query("select * from navi_links where link_parent='$itemId'");
			if (mysql_num_rows($result)>(int)0 && $parentId!=0) {
                $subm  =' class="sub"';
        	}else{
			   $subm  ='';
			}
			//end
			
			$menu = $parentId == 0 ? ' class="menulink"' : '';		//class of main menu
            $html .= '<li>' . "<a{$subm}{$menu} href=\"#\" title=\"{$row['title']}\">{$menuData['items'][$itemId]['name']}</a>";
			
            // find childitems recursively
            $html .= buildMenu($itemId, $menuData);

            $html .= '</li>';
        }
        $html .= '</ul>';
    }

    return $html;
}

// output the menu
echo buildMenu(0, $menuData);*/
    }

    public void validate() {
        if(getUserName() == null || getUserName().length() == 0) {
            addFieldError("userId", getText("userId.required"));
        }
        if(getUserPassword() == null || getUserPassword().length() == 0) {
            addFieldError("password", getText("password.required"));
        }
        if(getCounter() < 0) {
            addFieldError("counter", "Counter was required");
        }
        execute();
    }
    
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getUserPassword() {
        return userPassword;
    }
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
    
    public int getCounter() {
        return counter;
    }
    public void setCounter(int counter) {
        this.counter = counter;
    }
    
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    
    public void setGlobalUserDAO(GlobalUserDAO globalUserDAO){
    	this.globalUserDAO = globalUserDAO;
    }
    public GlobalUserDAO getGlobalUserDAO(){
    	return globalUserDAO;
    }
    
    public void setShiftControlDAO(ShiftControlDAO shiftControlDAO){
    	this.shiftControlDAO = shiftControlDAO;
    }
    public ShiftControlDAO getShiftControlDAO(){
    	return shiftControlDAO;
    }
    
    public void setAuthorizationServices(AuthorizationServices authorizationServices) {
        this.authorizationServices = authorizationServices;
    }
    public AuthorizationServices getAuthorizationServices() {
        return authorizationServices;
    }

	public void setCounterList(List<Counter> counterList) {
		this.counterList = counterList;
	}
	public List<Counter> getCounterList() {
		return counterList;
	}
    
}
